package com.example.demo.MyBlockingQueue;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-09-11
 * Time: 17:04
 */
public class MyBlockingQueue2<E> implements BlockingQueue<E> {
    // 队列主体
    private final E[] array;
    // 头指针
    private int head;
    // 尾指针
    private int tail;
    // 实际元素个数
    private int size;
    // 锁对象
    private ReentrantLock lock = new ReentrantLock();
    // 头waits ->配合poll使用,当为空了进入headWaits
    private Condition headWaits = lock.newCondition();
    // 尾waits -->配合offer使用,当慢了,进入tailWaits
    private Condition tailWaits = lock.newCondition();

    public MyBlockingQueue2(int capacity) {
        array = (E[]) new Object[capacity];
    }

    private boolean isFull() {
        return size == array.length;
    }

    private boolean isEmpty() {
        return size == 0;
    }


    @Override
    public void offer(E e) throws InterruptedException {
        lock.lockInterruptibly();
        try {
            while (isFull()) {
                tailWaits.await();
            }
            array[tail] = e;
            if (++tail == array.length) {
                tail = 0;
            }
            size++;
            headWaits.signal();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public boolean offer(E e, long timeout) throws InterruptedException {
        lock.lockInterruptibly();
        long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);
        try {
            while (isFull()) {
                if (nanos <= 0) {
                    return false;
                }
                nanos = tailWaits.awaitNanos(nanos);
            }
            array[tail] = e;
            if (++tail == array.length) {
                tail = 0;
            }
            size++;
            headWaits.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public E poll() throws InterruptedException {
        lock.lockInterruptibly();
        E e;
        try {
            while (isEmpty()) {
                headWaits.await();
            }
            // 取出对头元素
            e = array[head];
            array[head] = null;//方便GC
            if (++head == array.length) {
                head = 0;
            }
            size--;
            tailWaits.signal();
            return e;
        } finally {
            lock.unlock();
        }
    }
    @Override
    public String toString() {
        return "MyBlockingQueue{" +
                "queue=" + Arrays.toString(array);
    }
}